package com.ruoyi.novel.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.novel.domain.*;
import com.ruoyi.novel.mapper.*;
import com.ruoyi.novel.service.IBrokerageService;
import com.ruoyi.novel.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.novel.service.IOrderService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 会员订单Service业务层处理
 *
 * @author 张三
 * @date 2025-04-18
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService
{
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private VipMapper vipMapper;

    @Autowired
    private IntegralMapper integralMapper;

    @Autowired
    private FriendsMapper friendsMapper;

    @Autowired
    private CommunityMapper communityMapper;

    @Autowired
    private NovelMapper novelMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private IBrokerageService brokerageService;

    /**
     * 查询会员订单
     *
     * @param id 会员订单主键
     * @return 会员订单
     */
    @Override
    public Order selectOrderById(Integer id)
    {
        return orderMapper.selectOrderById(id);
    }

    /**
     * 查询会员订单列表
     *
     * @param order 会员订单
     * @return 会员订单
     */
    @Override
    public List<Order> selectOrderList(Order order)
    {
        return orderMapper.selectOrderList(order);
    }

    /**
     * 新增会员订单
     *
     * @param order 会员订单
     * @return 结果
     */
    @Override
    public int insertOrder(Order order)
    {
        order.setCreateTime(DateUtils.getNowDate());
        return orderMapper.insertOrder(order);
    }

    /**
     * 修改会员订单
     *
     * @param order 会员订单
     * @return 结果
     */
    @Override
    public int updateOrder(Order order)
    {
        order.setUpdateTime(DateUtils.getNowDate());
        return orderMapper.updateOrder(order);
    }

    /**
     * 批量删除会员订单
     *
     * @param ids 需要删除的会员订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderByIds(Integer[] ids)
    {
        return orderMapper.deleteOrderByIds(ids);
    }

    /**
     * 删除会员订单信息
     *
     * @param id 会员订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderById(Integer id)
    {
        return orderMapper.deleteOrderById(id);
    }

    @Override
    @Transactional
    public AjaxResult createOrder(Order order) {
        Integer userId = order.getUserId();
        User user = userService.getById(userId);
        order.setPhone(user.getPhone());
        String format = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        order.setOrderNum(format+ userId);

        AjaxResult result = AjaxResult.success("添加成功");
        Vip vip = new Vip();
        Integral integral = new Integral();
        if(order.getMode() == 0){
            //会员订单
            vip = vipMapper.selectById(order.getVipId());
            if(vip == null){
                return AjaxResult.error("会员信息有误");
            }
            order.setMoney(vip.getMoney());
            result.put("vip",vip);
        }else if(order.getMode() == 1){
            //充值订单
            integral = integralMapper.selectById(order.getIntegralId());
            if(integral == null){
                return AjaxResult.error("充值信息有误");
            }
            order.setLevel(0);
            order.setMoney(integral.getMoney());
            result.put("integral",integral);
        }else if(order.getMode() == 2){
            //积分订单
            if(order.getFriendsId() != null && order.getFriendsId() > 0){
                //交友订单
                Friends friends = friendsMapper.selectById(order.getFriendsId());
                if(order.getFriendsType() == 0){
                    //QQ
                    order.setMoney(friends.getIntegralQq());
                }
                if(order.getFriendsType() == 1){
                    //微信
                    order.setMoney(friends.getIntegralWx());
                }
                if(order.getFriendsType() == 2){
                    //手机号
                    order.setMoney(friends.getIntegralPhone());
                }
                if(order.getMoney().doubleValue() == 0.0){
                    order.setState(10);
                }
            }else if (order.getCommunityId() != null && order.getCommunityId() > 0){
                //社区文章
                Community community = communityMapper.selectById(order.getCommunityId());
                order.setMoney(community.getIntegral());
                if(community.getIntegral().doubleValue() == 0.0){
                    order.setState(10);
                }
            }else if (order.getNovelId() != null && order.getNovelId() > 0){
                //小说
                Novel novel = novelMapper.selectById(order.getNovelId());
//                order.setMoney(novel.getIntegral());
                if(novel.getIntegral().doubleValue() == 0.0){
                    order.setState(10);
                }
            }
        }
        order.setCreateTime(DateUtils.getNowDate());
        if(order.getType() == 1){
            order.setState(10);
            orderMapper.insertOrder(order);
            return result;
        }else {
            if(order.getState() == 10){
                orderMapper.insertOrder(order);
                AjaxResult success = AjaxResult.success("支付成功");
                success.put("code", 201);
                return success;
            }else {
                if(order.getMode() == 2){
                    //判断用户积分
                    if(user.getMoney().doubleValue() < order.getMoney().doubleValue()){
                        //积分不足
                        AjaxResult error = AjaxResult.error("积分不足");
                        error.put("code", 501);
                        return error;
                    }
                    //积分充足
                    boolean update = userService.update(new UpdateWrapper<User>().eq("id", user.getId()).setSql("money = money -" + order.getMoney().doubleValue()));
                    if(update){
                        order.setState(10);
                        //给上级分成
                        commissionOrder(order);
                    }
                }
                orderMapper.insertOrder(order);
                return AjaxResult.success("下单成功，请支付");
            }
        }
    }

    //订单分成
    @Transactional
    public void commissionOrder(Order order){
        Integer userId = order.getUserId();
        List<Brokerage> list = new ArrayList<>();
        User user1 = null;
        User user2 = null;
        User user3 = null;
        List<User> userList = userService.list(new QueryWrapper<User>().apply("find_in_set(id, (SELECT ancestors FROM a_user WHERE id = " + userId + "))"));
        for(User user : userList){
            int length = user.getAncestors().split(",").length;
            if(length == 1){
                //一级分销
                user1 = user;
            }else if(length == 2){
                //二级分销
                user2 = user;
            }else if(length == 3){
                //三级分销
                user3 = user;
            }else{
                //非分销或被四级分销邀请，不分成
            }
        }
        //计算订单分成金额
        BigDecimal money = order.getMoney();
        //三级分销应该拿的钱
        BigDecimal fen3 = BigDecimal.valueOf(0);
        if(user3 != null){
            fen3 = money.multiply(user3.getCommission());
            list.add(saveBrokerage(order,user3, fen3));
        }
        //二级分销应该拿的钱
        BigDecimal fen2 = BigDecimal.valueOf(0);
        if(user2 != null){
            fen2 = money.multiply(user2.getCommission()).subtract(fen3);
            list.add(saveBrokerage(order,user2, fen2));
        }
        //二级分销应该拿的钱
        BigDecimal fen1 = BigDecimal.valueOf(0);
        if(user1 != null){
            fen1 = money.multiply(user1.getCommission()).subtract(fen3).subtract(fen2);
            list.add(saveBrokerage(order,user1, fen1));
        }
        if(!list.isEmpty()){
            brokerageService.saveBatch(list);
        }
    }

    public Brokerage saveBrokerage(Order order, User user, BigDecimal money){
        Brokerage brokerage = new Brokerage();
        brokerage.setUserId(user.getId());
        brokerage.setIntegralId(order.getIntegralId());
        brokerage.setVideoId(order.getVideoId());
        brokerage.setFriendsId(order.getFriendsId());
        brokerage.setCommunityId(order.getCommunityId());
        brokerage.setNovelId(order.getNovelId());
        brokerage.setVipId(order.getVipId());
        brokerage.setFriendsType(order.getFriendsType());
        brokerage.setLevel(order.getLevel());
        brokerage.setType(order.getType());
        brokerage.setMode(order.getMode());

        brokerage.setMoney(money);
        brokerage.setState(0);
        brokerage.setCreateTime(new Date());

        //用户增加余额
        userService.update(new UpdateWrapper<User>().eq("id", user.getId()).setSql("money = money +"+ money));
        return brokerage;
    }
}
